const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const cors = require('cors');
const csv = require('csv-writer').createObjectCsvWriter;

const app = express();
const PORT = 3000;

// 启用 CORS
app.use(cors());
app.use(express.json());

// 读取设置文件
const SETTINGS_FILE = path.join(__dirname,'settings.json');

// 获取设置
app.get('/settings', async (req, res) => {
    try {
        const data = await fs.readFile(SETTINGS_FILE, 'utf8');
        const settings = JSON.parse(data);
        res.json(settings);
    } catch (error) {
        if (error.code === 'ENOENT') {
            // 如果文件不存在，返回默认设置
            const defaultSettings = {
                extraction: {
                    scan1: [1, 10],
                    scan2: [1, 10]
                },
                compare: {
                    compare1: [5, 16, 15, 26],
                    compare2: [38, 38, 28, 28]
                }
            };
            res.json(defaultSettings);
        } else {
            console.error('读取设置失败:', error);
            res.status(500).json({ 
                error: '读取设置失败',
                stack: process.env.NODE_ENV === 'development'? error.stack : undefined
            });
        }
    }
});

// 保存设置
app.post('/settings', async (req, res) => {
    try {
        // 验证数据结构
        if (!req.body.extraction ||!req.body.compare) {
            throw new Error("无效的请求格式");
        }
        await fs.writeFile(SETTINGS_FILE, JSON.stringify(req.body, null, 2), 'utf8');
        res.json({ success: true });
    } catch (error) {
        console.error('设置保存失败:', error);
        res.status(500).json({ 
            error: error.message || '服务器内部错误',
            stack: process.env.NODE_ENV === 'development'? error.stack : undefined
        });
    }
});

// 处理根路径，返回 index.html 文件
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

// 处理 /settings.html 路径，返回 settings.html 文件
app.get('/settings.html', (req, res) => {
    res.sendFile(path.join(__dirname, 'settings.html'));
});

// 保存绑定成功的数据
app.post('/save-binding-data', async (req, res) => {
    try {
        console.log('开始保存绑定数据...');
        const now = new Date();
        const year = String(now.getFullYear()).slice(-2);
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');

        const dataDir = path.join(__dirname, 'Data', `${year}${month}`);
        console.log('目标数据目录:', dataDir);
        // 检查年月文件夹是否存在，不存在则创建
        try {
            await fs.access(dataDir);
            console.log('数据目录已存在:', dataDir);
        } catch (accessError) {
            if (accessError.code === 'ENOENT') {
                console.log('数据目录不存在，开始创建:', dataDir);
                await fs.mkdir(dataDir, { recursive: true });
                console.log('数据目录创建成功:', dataDir);
            } else {
                throw accessError;
            }
        }

        const fileName = `${year}${month}${day}.csv`;
        const filePath = path.join(dataDir, fileName);
        console.log('目标 CSV 文件路径:', filePath);

        let fileExists = false;
        try {
            await fs.access(filePath);
            fileExists = true;
        } catch (fileAccessError) {
            if (fileAccessError.code === 'ENOENT') {
                fileExists = false;
            } else {
                throw fileAccessError;
            }
        }

        const csvWriter = csv({
            path: filePath,
            header: [
                { id: 'date', title: 'Date' },
                { id: 'sn1', title: 'SN1' },
                { id: 'sn2', title: 'SN2' }
            ],
            append: fileExists
        });

        const records = [
            {
                date: now.toLocaleString(),
                sn1: req.body.scan1,
                sn2: req.body.scan2
            }
        ];

        console.log('开始写入 CSV 文件...');
        await csvWriter.writeRecords(records);
        console.log('CSV 文件写入成功:', filePath);
        res.json({ success: true });
    } catch (error) {
        console.error('保存绑定数据失败:', error);
        res.status(500).json({ 
            error: error.message || '服务器内部错误',
            stack: process.env.NODE_ENV === 'development'? error.stack : undefined
        });
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});    